package com.yangkunhong.controller;

import com.yangkunhong.constant.ErrMsg;
import com.yangkunhong.utils.DateUtils;
import com.yangkunhong.utils.JSONUtils;
import com.yangkunhong.utils.UploadUtils;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;  
import org.apache.commons.fileupload.servlet.ServletFileUpload;  
  
import javax.servlet.ServletException;  
import javax.servlet.annotation.MultipartConfig;  
import javax.servlet.annotation.WebServlet;  
import javax.servlet.http.HttpServlet;  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  
import java.io.File;  
import java.io.IOException;  
import java.util.List;  
  
@WebServlet("/upload")  
@MultipartConfig  
public class UploadServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        req.getRequestDispatcher("/frontend/upload.jsp").forward(req, resp);
    }

    private static final long serialVersionUID = 1L;
  
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        if (!ServletFileUpload.isMultipartContent(request)) {  
            // 如果不是 multipart/form-data 请求，则处理错误  
            throw new ServletException("Content type is not multipart/form-data");  
        }  
  
        DiskFileItemFactory factory = new DiskFileItemFactory();  
        ServletFileUpload upload = new ServletFileUpload(factory);  
  
        try {  
            List<FileItem> items = upload.parseRequest(request);  
            for (FileItem item : items) {  
                if (!item.isFormField()) {
                    // 如果不是普通表单字段（即文件）
                    long fileSize = item.getSize();
                    // 获取文件大小（以字节为单位）
                    String contentType = item.getContentType(); // 获取文件 MIME 类型
                    // 输出文件信息
//                    System.out.println("文件名: " + item.getName());
//                    System.out.println("文件大小: " + fileSize + " 字节");
//                    System.out.println("MIME 类型: " + contentType);

                    String fileName = new File(item.getName()).getName(); // 获取文件名

//                    System.out.println("getFileUUIDName:"+UploadUtils.getFileUUIDName(fileName));
                    String filePath = "D:/javaweb/uploads/"+ DateUtils.getLocalDateAsDir()+"/" + UploadUtils.getFileUUIDName(fileName); // 设置文件保存路径
                   System.out.println("getImageInfo:"+UploadUtils.getImageInfo(item.getInputStream()));
//
                    File storeFile = new File(filePath);
                //    System.out.println(storeFile.getPath());
                    // 保存文件到指定位置  
                    item.write(storeFile);  
  
                    // 这里可以添加更多逻辑，如将文件信息保存到数据库等

                    Thumbnails.of(new File(filePath))
                            .size(160, 160)
                            .toFile(new File("D:/javaweb/uploads/"+ DateUtils.getLocalDateAsDir()+"/thumb_" + UploadUtils.getFileUUIDName(fileName)));
                }  
            }
            //调用DAO层，将文件信息保存到数据库
            JSONUtils.sendJsonStr(ErrMsg.UPLOAD_OK,response);
  
        } catch (Exception e) {
            e.printStackTrace();
            JSONUtils.sendJsonStr(ErrMsg.ERROR,response);
        }
    }  
}